package com.example.mqttxprovider.callback;

import com.example.mqttxprovider.service.MessageService;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Component
    public class MqttConsumerCallBack implements MqttCallback {

    @Autowired
    private MessageService messageService;
    private static ConcurrentMap<String,String> concurrentMap = new ConcurrentHashMap<>();
    @Override
    public void connectionLost(Throwable throwable) {
        System.out.println("与服务器断开连接，可重连");
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        try {
            System.out.println(String.format("接收消息主题 : %s",topic));
            System.out.println(String.format("接收消息Qos : %d",mqttMessage.getQos()));
            System.out.println(String.format("接收消息内容 : %s",new String(mqttMessage.getPayload())));
            System.out.println(String.format("接收消息retained : %b",mqttMessage.isRetained()));

            concurrentMap.put(topic,new String(mqttMessage.getPayload()));
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        System.out.println(String.format("接收消息成功"));
    }

    public String getMesByTopic(String topic){
        return concurrentMap.get(topic);
    }

}
